// pages/ocr/ocr.js
//获取应用实例
const app = getApp()
let utils = require('../../../utils/util.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isShowPop: false, //是否显示弹窗
    isShowMask: false, //是否显示遮罩
    isShowCamera: false, //是否显示camera组件
    isChoicePicture: false, //是否是选择图片
    forwardIdCardSrc: '../../../images/liveAuthentication/ocr/cgt-forward-up-img-bg.jpg', //身份证正面图片路径
    behindIdCardSrc: '../../../images/liveAuthentication/ocr/cgt-behind-up-img-bg.jpg', //身份证背面图片路径
    idCardType: 0, //身份证照片的类型，0为正面，1为反面
    cameraMoreMaskHeight: '152', //为了兼容特加的高度
    upForwardIdCardSuccess: false, //上传正面图片成功
    upBehindIdCardSuccess: false, //上传背面图片成功
    popSuccessNum: 3, //提交成功数字倒计时
    isShowPopSuccess: false, //是否显示成功提示
    isNavigateTo: false, //是否以及点击了页面跳转
    navigateToTimer: null, //跳转定时器timer
    trueImgUrl: '',
    cameraWidth: null,
    cameraHeight: '199',
    ctx: null, //相机对象
    UserName: '', //身份证名称
    IdNum: '', //身份证号码
    CertificatePath: '', //身份证正面图片路径 
    CertificateBackPath: '', //身份证背面图片路径
    modalHidden: true, //是否隐藏模态框
    modalMsg: '确认删除图片吗？', //模态框信息提示语
    currentDelImgId: null, //当前要删除图片的id
    isShowLoading: false, //是否显示加载中
    loadingText: '证件识别中...', //加载中文本显示
    isAuthority: false, //判断是否授权了，不授权不让认证
    windowWidth: app.systemInfo.windowWidth
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let self = this;

    //查询是否获取相机权限
    //当页面查询到有camera标签时，会默认进行是否进行授权弹窗提示
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.camera']) {
          //console.log('用户没有授权camera');
          //没有授权camera就先进行授权
          self.setData({
            isAuthority: false
          })
        } else {
          //console.log('用户已经授权camera');
          const ctx = wx.createCameraContext();
          self.setData({
            ctx: ctx,
            isAuthority: true
          });
        }
      },
      fail() {
        self.setData({
          isAuthority: false
        })
      }
    })
  },

  /**
   *  判断是否获取相机权限
   */
  isGetCameraAuthority: function () {
    let self = this;
    //判断是否获取相机权限
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.camera']) {
          //console.log('用户没有授权camera');
          //没有授权camera就先进行授权
          wx.authorize({
            scope: 'scope.camera',
            success() {
              const ctx = wx.createCameraContext();
              self.setData({
                ctx: ctx,
                isAuthority: true
              });
            },
            fail() {
              self.openConfirm();
              self.setData({
                isAuthority: false
              })
            }
          });
        } else {
          //console.log('用户已经授权camera');
          const ctx = wx.createCameraContext();
          self.setData({
            ctx: ctx,
            isAuthority: true
          });
        }
      },
      fail() {
        self.setData({
          isAuthority: false
        })
      }
    })
  },
  /**
   *  提示用户开通授权
   */
  openConfirm: function () {
    let self = this;
    wx.showModal({
      title: '提示',
      content: '身份认证需要您同意摄像头授权，检测到您没打开车管通的摄像头权限，是否去设置打开？',
      success(res) {
        if (res.confirm) {
          //console.log('用户点击确定');
          wx.openSetting({
            success: (res) => {
              if (res.authSetting['scope.camera']) {
                //用户同意相机授权
                const ctx = wx.createCameraContext();
                self.setData({
                  ctx: ctx,
                  isAuthority: true
                });
              } else {
                //用户拒绝相机授权
                self.setData({
                  isAuthority: false
                })
              }
            },
            fail: () => {
              self.setData({
                isAuthority: false
              })
            }
          })
        } else if (res.cancel) {
          //console.log('用户点击取消');
          self.setData({
            isAuthority: false
          })
        }
      }
    })
  },
  /**
   *  上传身份证图片
   */
  upImgTap: function (e) {
    let self = this;
    let index = e.currentTarget.dataset.idcardtype;
    self.setData({
      idCardType: index
    });
    let isAuthority = self.data.isAuthority;
    if (isAuthority) {
      wx.showActionSheet({
        itemList: ['拍照', '从相册选择上传'],
        success(res) {
          if (res.tapIndex == 0) { //用户选择拍照          
            self.setData({
              isShowMask: true,
              isShowPop: true,
              isChoicePicture: false
            })
          } else if (res.tapIndex == 1) { //用户选择从相册中找         
            self.setData({
              isShowMask: true,
              isShowPop: true,
              isChoicePicture: true
            })
          }
        },
        fail(res) {
          //console.log(res.errMsg)
        }
      })
    } else {
      //未获取授权
      self.isGetCameraAuthority();
    }
  },
  /**
   *  拍摄图片
   */
  takePhoto: function () {
    let self = this;
    self.data.ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        let tempImagePath = res.tempImagePath;
        self.getLessLimitSizeImage(
          'pressCanvas',
          tempImagePath,
          0.1,
          app.systemInfo.windowWidth,
          (imgPath) => {
            self.fileUpload(imgPath);
            wx.getFileInfo({
              filePath: imgPath,
              success(res) {
                console.log("压缩后图片大小:", res.size / 1024, 'kb');
              }
            })
          });
        // 这里添加加载中的样式，给用户提示
        self.setData({
          isShowLoading: true
        })
      }
    });
    //用户选择的是拍照
    self.setData({
      isShowCamera: false,
      isShowPop: false,
      isShowMask: false
    })
  },
  /**
   *  关闭拍照
   */
  closeCameraTap: function () {
    let self = this;
    self.setData({
      isShowCamera: false
    })
    wx.showToast({
      title: '摄像头已关闭',
      icon: 'none',
      duration: 2000
    })
  },
  /**
   *  弹窗按钮点击
   */
  popBtnTap: function () {
    let self = this;
    let isChoicePicture = self.data.isChoicePicture;
    self.setData({
      isShowMask: false,
      isShowPop: false
    })
    if (isChoicePicture) {
      //用户选择从相册中选取
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'], //【原图，缩略图】
        sourceType: ['album'], //【相册】
        success(res) {
          // 这里添加加载中的样式，给用户提示
          self.setData({
            isShowLoading: true
          })
          // tempFilePath可以作为img标签的src属性显示图片
          let tempImagePath = res.tempFilePaths[0];
          // self.fileUpload(tempImagePath);
          self.getLessLimitSizeImage(
            'pressCanvas',
             res.tempFilePaths[0], 
             0.1, 
             app.systemInfo.windowWidth, 
             (imgPath)=>{
                 self.fileUpload(imgPath);
               wx.getFileInfo({
                 filePath: imgPath,
                 success(res) {
                   console.log("压缩后图片大小:", res.size / 1024, 'kb');
                 }
               })
             });
        },
        fail(err) {
          wx.showToast({
            title: '选择图片失败',
            icon: 'none',
            duration: 2000
          })
        }
      })
    } else {
      //用户选择的是拍照
      self.setData({
        isShowCamera: true
      })
    }
  },
  /**
   *  确认并提交
   */
  submitBtnTap: function () {
    let self = this;
    let url = app.apiBaseUrl + '/AuthenticationAI/AddUserAuth';
    //这里需要进行一个验证，查看用户是否进行了图片的上传
    //身份证正面图片上传成功标识
    let upForwardIdCardSuccess = self.data.upForwardIdCardSuccess;
    //身份证背面图片上传成功标识
    let upBehindIdCardSuccess = self.data.upBehindIdCardSuccess;
    if (upForwardIdCardSuccess && upBehindIdCardSuccess) {
      app.httpRequest({
        url: url,
        showLoading: false,
        method: "POST",
        data: {
          CertificatePath: self.data.CertificatePath,
          CertificateBackPath: self.data.CertificateBackPath,
          UserID: app.userInfo.UserID
        },
        success: function (res) {
          //用户提交成功，用户等级提升为1
          app.userInfo.AuthLevel = 1;
          //缓存更新一下
          app.setUserInfo(app.userInfo);
          //console.log(res);
          self.showTimer();
          //设置身份证正面
          wx.setStorageSync('IdCardImage', self.data.CertificatePath);
        }
      });
    } else {
      //用户身份证图片没有上传或者没有上传完整
      wx.showToast({
        title: '请先完成身份证照片的上传',
        icon: 'none',
        duration: 2000
      })
    }


  },
  /**
   * 显示倒计时
   */
  showTimer() {
    let self = this;
    self.setData({
      isShowMask: true,
      isShowPopSuccess: true
    })
    let popSuccessNum = self.data.popSuccessNum;
    let isNavigateTo = self.data.isNavigateTo;
    let timer = setInterval(function () {
      popSuccessNum--;
      self.setData({
        popSuccessNum: popSuccessNum
      })
      if (popSuccessNum <= 0 && !isNavigateTo) {
        clearInterval(timer);
        self.setData({
          isShowMask: false,
          isShowPopSuccess: false
        })
        self.nanavigateToVerCode();
      }
    }, 1000);
    self.setData({
      navigateToTimer: timer
    })
  },

  /**
   *  用户点击跳转
   */
  nanavigateToVerCode() {
    let self = this;
    let timer = self.data.navigateToTimer;
    //用户页面跳转标识
    clearInterval(timer);
    //console.log('timer', timer);
    self.setData({
      isNavigateTo: true
    })
    wx.navigateTo({
      url: '/pages/liveAuthentication/video/video?IdCardImage=' + self.data.CertificatePath,
    })
  },
  /**
   * 文件上传
   */
  fileUpload(tempFilePath) {
    const self = this;
    //console.log(app.userInfo.UserID)
    let idCardType = self.data.idCardType;
    const url = app.apiBaseUrl + '/AuthenticationAI/IdCardOCR';
    const uploadTask = wx.uploadFile({
      url: url, //仅为示例，非真实的接口地址
      filePath: tempFilePath,
      name: 'file',
      formData: {
        'UserID': app.userInfo.UserID, //用户
        'CardType': idCardType //身份证正反面
      },
      success: function (res) {
        var data = JSON.parse(res.data);
        if (data.status != 0) {
          wx.showToast({
            title: data.message,
            icon: 'none',
            duration: 2000
          })
          self.setData({
            // 这里上传成功关闭loading
            isShowLoading: false
          })
          return;
        }
        if (idCardType == 0) { //身份证正面         
          self.setData({
            UserName: data.data.Name,
            IdNum: data.data.Id,
            isShowCamera: false,
            upForwardIdCardSuccess: true,
            forwardIdCardSrc: tempFilePath,
            CertificatePath: data.data.ImgageName,
            // 这里上传成功关闭loading
            isShowLoading: false
          });
        } else if (idCardType == 1) { //身份证背面
          self.setData({
            isShowCamera: false,
            upBehindIdCardSuccess: true,
            behindIdCardSrc: tempFilePath,
            CertificateBackPath: data.data.ImgageName,
            // 这里上传成功关闭loading
            isShowLoading: false
          });
        }
      },
      fail: function (res) {
        //console.log(res)
      }
    });

    uploadTask.onProgressUpdate((res) => {
      //console.log('上传进度', res.progress)
      //console.log('已经上传的数据长度', res.totalBytesSent)
      //console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    })
  },
  /**
   *  删除上传图片
   */
  delImgTap: function (e) {
    let self = this;
    let src = e.currentTarget.dataset.src;
    //console.log(src);
    self.setData({
      modalHidden: false,
      currentDelImgId: src
    })
  },
  /**
   *  模态框确认按钮点击
   */
  modalSureListener: function () {
    let self = this;
    let src = self.data.currentDelImgId;
    switch (src) {
      case 'forwardIdCardSrc':
        self.setData({
          modalHidden: true,
          forwardIdCardSrc: '../../../images/liveAuthentication/ocr/cgt-forward-up-img-bg.jpg',
          upForwardIdCardSuccess: false
        })
        break;
      case 'behindIdCardSrc':
        self.setData({
          modalHidden: true,
          behindIdCardSrc: '../../../images/liveAuthentication/ocr/cgt-behind-up-img-bg.jpg',
          upBehindIdCardSuccess: false
        })
        break;
    }
  },
  /**
   *  浏览当前图片
   */
  previewImageTap: function (e) {
    let self = this;
    //console.log('图片预览');
    let src = e.currentTarget.dataset.src;
    let previewImageCurrent;
    switch (src) {
      case 'forwardIdCardSrc':
        previewImageCurrent = self.data.forwardIdCardSrc;
        break;
      case 'behindIdCardSrc':
        previewImageCurrent = self.data.behindIdCardSrc;
        break;
    }
    let previewImageUrls = [];
    //这三张图片只要有一张上传成功，就可以进行图片预览
    if (self.data.forwardIdCardSrc && self.data.upForwardIdCardSuccess) {
      previewImageUrls.push(self.data.forwardIdCardSrc);
    }
    if (self.data.behindIdCardSrc && self.data.upBehindIdCardSuccess) {
      previewImageUrls.push(self.data.behindIdCardSrc);
    }
    wx.previewImage({
      current: previewImageCurrent, // 当前显示图片的http链接
      urls: previewImageUrls // 需要预览的图片http链接列表
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let self = this;
    let windowHeight;
    wx.getSystemInfo({
      success(res) {
        //console.log('res.windowHeight', res.windowHeight);
        windowHeight = res.windowHeight;
      },
      fail(err) {
        //console.log('获取系统信息失败！');
      }
    })

    //获取相机信息
    let imgWidth = app.systemInfo.windowWidth;
    let imgHeight = parseInt(app.systemInfo.windowWidth * 451 / 722);
    let cameraMoreMaskHeight = (windowHeight - imgHeight) / 2;
    //console.log(windowHeight);
    self.setData({
      cameraWidth: imgWidth,
      cameraHeight: imgHeight,
      cameraMoreMaskHeight: cameraMoreMaskHeight
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },




  /**
   * 获取图片的大小信息
   * imagePath  图片地址
   * limitSize  图片限制大小  （M）
   * lessCallBack  小于这个图片限制大小的回调
   * moreCallBack  大于这个图片限制大小的回调
   */
  imageSizeIsLessLimitSize: function (imagePath, limitSize, lessCallBack, moreCallBack) {
    let self=this;
    wx.getFileInfo({
      filePath: imagePath,
      success(res) {
        console.log("压缩前图片大小:", res.size / 1024, 'kb');
        if (res.size > 1024 * 1024 * limitSize) {
          moreCallBack();
        } else {
          lessCallBack();
        }
      }
    })
  },

  /**
 * 获取小于限制大小的Image, limitSize默认为1M，递归调用。
 * canvasId  canvas的id
 * imagePath  图片地址
 * limitSize  图片限制大小（M）
 * drawWidth  canvas的宽度，最好为手机屏幕宽度
 * callBack  回调函数
 */
  getLessLimitSizeImage: function (canvasId, imagePath, limitSize, drawWidth, callBack) {
    let self=this;
    self.imageSizeIsLessLimitSize(imagePath, limitSize,
      (lessRes) => {
        callBack(imagePath);
      },
      (moreRes) => {
        wx.getImageInfo({
          src: imagePath,
          success: function (imageInfo) {
            var maxSide = Math.max(imageInfo.width, imageInfo.height);
            
            //画板的宽高默认是windowWidth
            var windowW = drawWidth;
            var scale = 1;
            if (maxSide > windowW) {
              scale = windowW / maxSide;
            }
            var imageW = Math.floor(imageInfo.width * scale);
            var imageH = Math.floor(imageInfo.height * scale);
            console.log('调用压缩', imageW, imageH);
            self.getCanvasImage(canvasId, imagePath, imageW, imageH,
              (pressImgPath) => {
                self.getLessLimitSizeImage(canvasId, pressImgPath, limitSize, drawWidth * 0.7, callBack);
              }
            );
          }
        })
      }
    )
  },


  /**
 * 获取画布图片 
 * canvasId  canvas的id
 * imagePath  图片地址
 * limitSize  图片限制大小（M）
 * imageW  canvas的宽度，最好为手机屏幕宽度
 * imageH  canvas的高度，最好为手机屏幕宽度
 * getImgsuccess  获取压缩后的图片地址
 */
  getCanvasImage: function (canvasId, imagePath, imageW, imageH, getImgsuccess) {
    let self=this;
    const ctx = wx.createCanvasContext(canvasId);
    ctx.drawImage(imagePath, 0, 0, imageW, imageH);
    ctx.draw(false, () => {
      wx.canvasToTempFilePath({
        canvasId: canvasId,
        x: 0,
        y: 0,
        width: imageW,
        height: imageH,
        quality: 1,
        success(res) {
          getImgsuccess(res.tempFilePath);
        },
        fail(res){
          console.log(res);
        }
      });
    });
  }
})